package com.loutick.pay.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.loutick.pay.dao.TOrderMapper;
import com.loutick.pay.dao.TPamentlogMapper;
import com.loutick.pay.dao.TUseraccountMapper;
import com.loutick.pay.dao.TUseraccountlogMapper;
import com.loutick.pay.entity.TOrder;
import com.loutick.pay.entity.TPamentlog;
import com.loutick.pay.entity.TUseraccount;
import com.loutick.pay.entity.TUseraccountlog;
import com.loutick.pay.service.IPamentlog;

@Service("pamentlogService")   
@Transactional
public class PamentlogServiceImpl implements IPamentlog { 
	
	@Resource
	private TPamentlogMapper pamentlogMapper ;
	
	@Resource
	private TUseraccountMapper useraccountMapper;
	
	@Resource
	private TUseraccountlogMapper useraccountlogMapper;
	
	@Resource
	private TOrderMapper orderMapper;
	
	 
	public int insertPamentlog(TPamentlog record) {
		return pamentlogMapper.insertSelective(record) ;
	}

	public TPamentlog selectByOuttradesn(String outtradesn) {
		
		return pamentlogMapper.selectByOuttradesn(outtradesn);
	}
	
	public int insertOrder(TOrder order){
		
		return orderMapper.insertSelective(order);
	}
	
	public TOrder selectByInfo(TOrder order) {
		
		return orderMapper.selectByInfo(order);
	}
	
	public String rechargeLog(String outtradesn,String tradeno){ 
		//查找pamentlog中的充值日志是否存在；
		TPamentlog tp = pamentlogMapper.selectByOuttradesn(outtradesn);
		if(tp == null) return "无支付日志";
		
		//修改pamentlog信息
		tp.setTradeno(tradeno);
		tp.setPaytime(new Date());
		tp.setPaystatus(1);
		pamentlogMapper.updateByPrimaryKeySelective(tp);
		
		String chargetype = "" ;
		chargetype = tp.getPaytotype();
		if(chargetype.equals("20")){
		
			Integer useraccountid = tp.getUseraccountid();
			//向对应用户账户充值；
			TUseraccount tUseraccount = useraccountMapper.selectByPrimaryKey(useraccountid);
			Integer newAmount = tUseraccount.getAmount()+tp.getPayamount();
			Integer oldAmount = tUseraccount.getAmount();
			tUseraccount.setAmount(newAmount);
			useraccountMapper.updateByPrimaryKeySelective(tUseraccount);
			//记录用户账户充值记录
			TUseraccountlog useraccountlog = new TUseraccountlog();
			useraccountlog.setAmount(tp.getPayamount());
			useraccountlog.setCurrentamount(oldAmount);
			useraccountlog.setChargetype("I01");
			useraccountlog.setLogtime(new Date());
			useraccountlog.setPaymentlogid(tp.getPaymentlogid());
			useraccountlog.setUseraccountid(useraccountid);
			useraccountlogMapper.insertSelective(useraccountlog);
			return "充值成功";
		}else if(chargetype.equals("10")){
			return "支付成功" ;
		}
		
		return "充值成功" ;
	}

	

}
